package apk.yoursms.download;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import apk.yoursms.R;
import apk.yoursms.Values;
import apk.yoursms.YourSms;
import apk.yoursms.database.SmsDbHelper;
import apk.yoursms.settings.NotificationUtils;

import com.StarsSDK.Utils.Utils;

public class DownloadService extends Service {

    public static final String BROADCAST_ACTION = "com.apk.download.DownloadService";

    // private BroadcastReceiver service = null;
    private ContentValues values = null;
    private final Handler handler = new Handler();
    private Bundle extras = null;
    private final int SMS_LOVE = 1;
    private final int SMS_SKANDAL = 2;
    private final int SMS_CONG = 3;
    private final int SMS_HUMOR = 4;

    ContentAdapter contentAdapter;
    Intent intent;
    ArrayList<Integer> catg;

    @Override
    public void onCreate() {
	super.onCreate();
	Log.d("SERVICE", "onCreate");

	contentAdapter = new ContentAdapter();
	NotificationUtils.setNotification(this,
		getString(R.string.default_base),
		Values.siteToString.get(Values.DEFAULT_SITE));

	intent = new Intent(BROADCAST_ACTION);
    }

    @Override
    public void onStart(Intent intent, int startId) {

    }

    @Override
    public void onDestroy() {
	handler.removeCallbacks(sendUpdatesToUI);
	super.onDestroy();
	Log.d("SERVICE", "Service destoyed.");

	NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	if (mNotificationManager != null) {
	    mNotificationManager.cancel(NotificationUtils._ID);
	}
	stopService(new Intent(this, DownloadService.class));
    }

    @Override
    public IBinder onBind(Intent intent) {
	return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
	Log.d("SERVICE", "onStartCommand");
	try {
	    extras = intent.getExtras();
	    catg = extras.getIntegerArrayList("catg");

	    handler.removeCallbacks(sendUpdatesToUI);
	    handler.postDelayed(sendUpdatesToUI, 1000);
	} catch (Exception e) {
	}

	return startId;
    }

    private void startDownload(ArrayList<Integer> category) {
	for (int ctg : category) {

	    values = new ContentValues();

	    try {
		switch (ctg) {
		case SMS_LOVE:
		    insertData(Values.SMS_LOVE_FILE, ctg);
		    break;

		case SMS_SKANDAL:
		    insertData(Values.SMS_SKANDAL_FILE, ctg);
		    break;

		case SMS_CONG:
		    insertData(Values.SMS_CONG_FILE, ctg);
		    break;

		case SMS_HUMOR:
		    insertData(Values.SMS_HUMOR_FILE, ctg);
		    break;

		default:
		    break;
		}

	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
    }

    private void insertData(String file, int ctg) throws Exception {
	String path = this.getString(R.string.local) + "/" + file;

	InputStream stream = null;
	try {
	    stream = this.getAssets().open(path);
	} catch (IOException e) {
	}

	BufferedReader dataStream = new BufferedReader(new InputStreamReader(
		stream, "UTF8"));
	String data = "";
	try {
	    while ((data = dataStream.readLine()) != null) {
		if ((data.contains("&web")) && Utils.isOnline()) {
		    insertDataFromWeb(data.split("&web")[0], ctg);

		    putValueInsert(data.split("&web")[0],
			    dataStream.readLine(), ctg, Values.DEFAULT_SITE);

		} else {
		    data = (data.contains("&web") ? data.split("&web")[0]
			    : data);
		    putValueInsert(data, dataStream.readLine(), ctg,
			    Values.DEFAULT_SITE);
		}
	    }

	} catch (Exception e) {
	}

	stream.close();
	dataStream.close();
    }

    private void insertDataFromWeb(String group, int ctg) throws Exception {
	String tableName = "";
	SharedPreferences prefs = PreferenceManager
		.getDefaultSharedPreferences(this.getBaseContext());

	ArrayList<String> sites = new ArrayList<String>();
	if (prefs.getBoolean("smska4u", false)) {
	    tableName = Values.SMSKA4U_RU_TABLE_NAME;
	    sites.add(tableName);
	}
	if (prefs.getBoolean("smskiby", false)) {
	    tableName = Values.SMSKI_BY_TABLE_NAME;
	    sites.add(tableName);
	}
	if (prefs.getBoolean("smsfunonline", false)) {
	    tableName = Values.SMS_FUNON_LINE_TABLE_NAME;
	    sites.add(tableName);
	}
	if (prefs.getBoolean("sms44", false)) {
	    tableName = Values.SMS_44_TABLE_NAME;
	    sites.add(tableName);
	}

	boolean isRuLang = this.getString(R.string.local)
		.equalsIgnoreCase("RU");

	String lang = "en";
	if (isRuLang) {
	    lang = "ru";
	}

	for (String site : sites) {

	    JSONArray json = null;
	    int retry = 3;
	    int count = 0;

	    String sgroup = URLEncoder.encode(group, "utf-8");
	    String mUrl = String.format("sms?sgroup=%s&cat=%s&site=%s&lang=%s",
		    sgroup, ctg, site, lang);
	    while (count < retry) {
		count += 1;
		try {
		    json = executeHttp(mUrl);
		} catch (Exception e) {
		    if (count >= retry) {
			Toast.makeText(this, "Oooops", Toast.LENGTH_LONG)
				.show();
		    }
		}
	    }

	    NotificationUtils.setNotification(this, group,
		    Values.siteToString.get(site));

	    String sms = Parse.init(json, site);
	    putValueInsert(group, sms, ctg, site);
	}

    }

    private JSONArray executeHttp(String url) {
	try {
	    YourSms app = (YourSms) this.getApplication();
	    HttpClient client = app.getHttpClient();
	    HttpGet request = new HttpGet();
	    String mUrl = Parse.MAIN_URL + url;
	    request.setURI(new URI(mUrl));
	    HttpResponse response = client.execute(request);
	    HttpEntity entity = response.getEntity();
	    String result = EntityUtils.toString(entity, HTTP.UTF_8);

	    JSONArray json_array = new JSONArray(result);

	    return json_array;
	} catch (Exception e) {
	    e.printStackTrace();
	}

	return null;
    }

    private void putValueInsert(String group, String array, int ctg, String site) {

	values.put(SmsDbHelper.GROUP, group);
	values.put(SmsDbHelper.SMS_TEXT, array);
	values.put(SmsDbHelper.SMS_CATEGORY, ctg);
	values.put(SmsDbHelper.SMS_SITE, site);

	this.getContentResolver().insert(
		Uri.parse("content://apk.yoursms.database.SmsProvider/"
			+ this.getString(R.string.tableName)), values);

	Log.d("SERVICE ctg", "" + ctg);
	intent.putExtra("ctg", ctg);
	sendBroadcast(intent);
    }

    private Runnable sendUpdatesToUI = new Runnable() {
	public void run() {

	    new Thread(new Runnable() {
		@Override
		public void run() {
		    ArrayList<Integer> catg = extras
			    .getIntegerArrayList("catg");
		    startDownload(catg);
		    stopService(new Intent(DownloadService.this,
			    DownloadService.class));
		}
	    }).start();

	}
    };

}
